package http;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 模拟登陆.
 *
 * @author 宫新程
 * @since 2018/12/23 10:44 PM
 */
public class TestHttp {

  private static ThreadLocal<String> cookieStr = new ThreadLocal<>();

  /** 测试 Http. */
  public static void main(String[] args) throws Exception {

    URL url = new URL("http://localhost:8080/login");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setConnectTimeout(1000 * 3000);
    connection.setReadTimeout(1000 * 3000);
    connection.setDoOutput(true);
    connection.setDoInput(true);

    // 设置 Request Header
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty(
        "User-Agent",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
    connection.setRequestMethod("POST");
    connection.setUseCaches(false);

    // 发送请求参数.
    PrintWriter out = new PrintWriter(connection.getOutputStream());
    out.print("username=admin&password=123qwe");
    out.flush();

    // 获取相应头
    if (connection.getResponseCode() == 200) {
      System.out.println("=================== 相应头 =====================");
      Map<String, List<String>> headerFields = connection.getHeaderFields();
      headerFields.forEach(
          (k, v) -> {
            System.out.println(k + "：");
            v.forEach(e -> System.out.println("\t\t" + e));
          });
      System.out.println("===========================================");

      // 获取cookie，将cookie放到 ThreadLocal中
      String cookie = connection.getHeaderFields().get("Set-Cookie").get(0);
      cookieStr.set(cookie);

      /** 获取相应体. */
      InputStream inputStream = connection.getInputStream();
      String result =
          new BufferedReader(new InputStreamReader(inputStream))
              .lines()
              .collect(Collectors.joining(System.lineSeparator()));
      System.out.println(result);
      System.out.println("===========================================");

      // 显示首页.
      showIndex();
    }
  }



  /** 登陆首页. */
  public static void showIndex() throws Exception {
    URL url = new URL("http://localhost:8080/index");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Cookie", cookieStr.get());
    conn.setRequestProperty(
        "User-Agent",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String content = in.lines().collect(Collectors.joining(System.lineSeparator()));
    System.out.println(content);
  }
}
